<template>
  <div>
    <!--搜索框-->
    <el-form :inline="true" :model="searchForm">
      <el-form-item>

        <el-switch
            v-model="bookPeriodical"
            active-text="图书"
            inactive-text="期刊"
            @change="switchChange">
        </el-switch>
      </el-form-item>
      <el-form-item>

        <el-input placeholder="请输入内容" v-model="searchForm.input" clearable @clear="getList">
          <el-select placeholder="请选择查询项" v-model="selectData" slot="prepend" style="width: 200px">
            <el-option v-if="!isUser" label="借阅者姓名" value="1"></el-option>
            <el-option label="图书或期刊名称" value="2"></el-option>
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="select">搜索</el-button>
        <el-button type="primary" @click="saveHandle" v-if="!isUser&&hasAuth('borrowRecord:manage:save')">新增</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table border stripe :data="tableData" tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="readerName" label="借阅者姓名"></el-table-column>
      <el-table-column width="150px" prop="bookCode" label="ISSN码或ISBN码"></el-table-column>
      <el-table-column width="150px" prop="name" label="图书或期刊名称"></el-table-column>
      <el-table-column v-if="!bookPeriodical" label="期数" prop="issue"></el-table-column>
      <el-table-column width="200px" prop="typeName" label="类别"></el-table-column>
      <el-table-column prop="borrowDate" label="借阅日期"></el-table-column>
      <el-table-column prop="shouldReturnDate" label="应还日期"></el-table-column>
      <el-table-column prop="returnDate" label="实还日期"></el-table-column>
      <el-table-column prop="state" label="借阅状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state === 0" size="small" type="info">未归还</el-tag>
          <el-tag v-else-if="scope.row.state === 1" size="small" type="success">已归还</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="100px" label="操作" v-if="hiddenTableCol">
        <template slot-scope="scope">
          <el-popconfirm v-if="scope.row.state===0" title="确定要归还该书籍吗？" @confirm="returnHandle(scope.row.id)">
            <el-button type="text" slot="reference">还书</el-button>
          </el-popconfirm>
          <el-divider direction="vertical"
                      v-if="scope.row.state===0&&isUser===0&&hasAuth('borrowRecord:manage:update')&&pagePerms.length>1"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id)" v-if="isUser===0&&hasAuth('borrowRecord:manage:update')">
            编辑
          </el-button>
          <el-divider direction="vertical"
                      v-if="isUser===0&&hasAuth('borrowRecord:manage:delete')&&pagePerms.length>1"></el-divider>
          <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.id)"
                         v-if="isUser===0&&hasAuth('borrowRecord:manage:delete')">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--页码-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current"
                   :page-sizes="[10, 20, 50, 100]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
                   :total="total"></el-pagination>

    <el-dialog title="借阅信息" :visible.sync="dialogFormVisible" width="600px">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-alert v-if="isUpdate" title="不允许修改借阅图书或期刊、借阅者以及借阅时间，如有需要请删除无用记录重新添加" :closable="false" type="info"
                  style="line-height: 12px;"></el-alert>
        <el-form-item v-if="isUpdate" label="实还日期" prop="returnDate" label-width="100px">
          <el-input type="date" v-model="editForm.returnDate" autocomplete="off"></el-input>
          <el-alert title="未归还则实还日期为空" :closable="false" type="info"
                    style="line-height: 12px;"></el-alert>
        </el-form-item>
        <el-form-item v-if="isUpdate" label="应还日期" prop="shouldReturnDate" label-width="100px">
          <el-input type="date" v-model="editForm.shouldReturnDate" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="isUpdate" label="借阅状态" prop="state" label-width="100px">
          <el-radio-group v-model="editForm.state">
            <el-radio :label="0">未归还</el-radio>
            <el-radio :label="1">已归还</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!isUpdate" label="借阅人姓名" prop="readerId" label-width="150px">
          <el-select v-model="editForm.readerId" filterable placeholder="请输入借阅人手机号并选择">
            <el-option
                v-for="item in readerOptions"
                :key="item.id"
                :label="item.reader"
                :value="item.id">
            </el-option>
          </el-select>
          <el-alert v-if="isUpdate" title="括号内为用户名" :closable="false" type="info"
                    style="line-height: 12px;"></el-alert>
        </el-form-item>
        <el-form-item v-if="!isUpdate" label="图书或期刊" prop="bookId" label-width="150px">
          <el-select @change="changeIssnHandle" v-model="editForm.bookId" filterable placeholder="请输入并选择图书或期刊">
            <el-option
                v-if="bookPeriodical"
                v-for="item in bookOptions"
                :key="item.id"
                :label="item.name+'（'+item.isbn+')'"
                :value="item.id"
            >
            </el-option>

            <el-option
                v-if="!bookPeriodical"
                v-for="item in bookOptions"
                :key="item.id"
                :label="item.name+'（'+item.issn+')'"
                :value="item.id"
            >
            </el-option>
            <el-alert v-if="isUpdate" title="括号内为图书的ISBN码或期刊ISSN码" :closable="false" type="info"
                      style="line-height: 12px;"></el-alert>
          </el-select>
        </el-form-item>

        <el-form-item v-if="!bookPeriodical&&editForm.bookId" label="期数" prop="issue" label-width="150px">
          <el-select v-model="editForm.issue" filterable placeholder="请输入并选择期数">
            <el-option
                v-if="!bookPeriodical"
                v-for="item in periodicalData.periodicalList"
                :key="item.id"
                :label="item.issue"
                :value="item.issue">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import qs from "qs";

export default {
  name: "borrowRecord",
  data() {
    return {
      //搜索框表单
      searchForm: {input: null},
      //编辑表单
      editForm: {},
      issueIndex: null,
      //编辑表单规则
      editFormRules: {
        bookId: [{required: true, message: '请选择图书或期刊', trigger: 'blur'}],
        issue: [{required: true, message: '请选择期数', trigger: 'blur'}],
        readerId: [{required: true, message: '请选择借阅人', trigger: 'blur'}],
        shouldReturnDate: [{required: true, message: '请输入应还日期', trigger: 'blur'}],
        state: [{required: true, message: '请选择借阅状态', trigger: 'blur'}],
      },
      //当前页，默认为1
      current: 1,
      //记录总数，默认为0
      total: 0,
      //每页记录数，默认每页10条
      size: 10,
      //是否显示编辑/新增dialog
      dialogFormVisible: false,
      //表格数据
      tableData: [],
      //当前页需要的权限列表，只包括按钮类型
      pagePerms: [],
      //隐藏表格操作类
      hiddenTableCol: false,
      //选中的行数组
      multipleSelection: [],
      //是否选择记录，如果否则禁用批量删除按钮
      delBtnStu: true,
      isUpdate: false,
      bookOptions: [],
      readerOptions: [],
      selectData: null,
      bookPeriodical: true,
      periodicalData: {},
      isReturn: false,
      isUser: 0
    }
  },
  methods: {
    returnHandle(id) {
      this.$axios.put("/borrowRecord/" + id).then((res) => {
        const loading = this.$loading({
          lock: true,
          text: 'loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        loading.close();
        this.$message({
          showClose: true, message: '恭喜你，归还成功', type: 'success', duration: 2000, onClose: () => {
            this.getList()
          }
        });
      });
    },
    select() {
      this.current = 1;
      this.getList()
    },
    switchChange() {
      this.current = 1;
      this.getList()
    },
    saveHandle() {
      this.isUpdate = false;
      this.resetForm('editForm');
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let i = this.bookPeriodical ? 0 : 1
      this.$axios.get("/borrowRecord/readerAndBook/" + i).then(res => {
        loading.close();
        this.bookOptions = res.data.data.bookOptions
        this.readerOptions = res.data.data.readerOptions
        this.dialogFormVisible = true
      })
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    changeIssnHandle(id) {
      if (!this.bookPeriodical) {
        const loading = this.$loading({
          lock: true,
          text: 'loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$axios.get("/periodical/info/" + id).then(res => {
          loading.close();
          this.periodicalData = res.data.data
        })
      }
    },
    getList() {
      let params = {
        current: this.current,
        size: this.size,
        user: this.isUser
      }
      if (this.selectData === "1") {
        params.readerName = this.searchForm.input;
      } else {
        params.name = this.searchForm.input;
      }
      params.bookPeriodical = this.bookPeriodical ? 0 : 1;
      this.$axios.get('/borrowRecord', {
        params: params
      }).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getList()
    },
    submitEditForm: function (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          console.log(this.editForm)

          this.$set(this.editForm, 'bookPeriodical', this.bookPeriodical ? 0 : 1);
          let data;
          if (this.editForm.id) {
            data = {
              id: this.editForm.id,
              shouldReturnDate: this.editForm.shouldReturnDate,
              returnDate: this.editForm.returnDate,
              state: this.editForm.state,
            }
          }

          console.log(this.editForm)
          this.$axios({
            method: this.editForm.id ? 'put' : 'post',
            url: '/borrowRecord',
            data: this.editForm.id ? data : this.editForm
          }).then(res => {
            loading.close();
            this.resetForm(formName)
            this.$message({
              showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
                this.getList()
              }
            });
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandle(id) {
      this.isUpdate = true;
      this.resetForm('editForm');
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$axios.get("/borrowRecord/info/" + id).then(res => {
        loading.close();
        this.editForm = res.data.data
        this.dialogFormVisible = true
      })
    },
    delHandle(id) {
      this.$axios.delete("/borrowRecord", {
        params: {
          id: id,
        },
        paramsSerializer: params => {
          return qs.stringify(params, {indices: false})
        }
      }).then(res => {
        this.$message({
          showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
            this.getList()
          }
        });
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.editForm = {}
      this.issueIndex = null
      this.bookOptions = {};
    },
  },
  activated() {
    if (this.$route.path === '/myBorrowRecords') {
      this.isUser = 1;
    } else {
      this.isUser = 0;
    }
    console.log(this.isUser)
  },
  created() {
    this.getList();
    this.hiddenTableCol = this.isUser || this.hasAuth('borrowRecord:manage:update') || this.hasAuth('borrowRecord:manage:delete')
    this.pagePerms = this.getPagePerms(this.$route.name);
    this.selectData = "2"
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 20px;
  padding-bottom: 30px;

}

.drawer-p {
  margin-left: 20px;
}
</style>
